﻿using Noria.Net.Chaos.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Noria.Net.Chaos.Net
{
    class ForwardWorker
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static readonly IEnumerable<IRule> rules = CreateTamperRules();

        private TcpClient client;
        private TcpClient server;
        private EndPoint clientEndPoint;
        private EndPoint serverEndPoint;
        private SemaphoreSlim semaphore;

        public ForwardWorker(SemaphoreSlim semaphore, TcpClient client, TcpClient server)
        {
            this.semaphore = semaphore;
            this.client = client;
            this.server = server;
            this.clientEndPoint = client.Client.RemoteEndPoint;
            this.serverEndPoint = server.Client.RemoteEndPoint;

            new HeadlessForwarder(client, server, null).Start();
            new HeadlessForwarder(server, client, rules).Start();

            log.DebugFormat("ForwardWorker started on {0} -> {1}", clientEndPoint, serverEndPoint);
        }

        private static ICollection<IRule> CreateTamperRules()
        {
            return Settings.Default.TamperRules.Cast<String>().Select(p =>
            {
                var cc = p.Split('|');
                return new TamperRule(cc[0], cc[1]);
            }).ToArray();
        }

        internal void Cancel()
        {
            client.Close();
            server.Close();

            log.DebugFormat("ForwardWorker stopped on {0} -> {1}", clientEndPoint, serverEndPoint);
        }
    }
}
